using Beauty.Net.Ocelot.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using Ocelot.Middleware;
using Ocelot.Administration;

namespace Beauty.Net.Ocelot;

/// <summary>
/// Ocelot应用程序构建器扩展
/// </summary>
public static class OcelotApplicationBuilderExtensions
{
    /// <summary>
    /// 使用Ocelot网关中间件
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder UseOcelotGateway(this IApplicationBuilder app)
    {
        var options = app.ApplicationServices.GetRequiredService<IOptions<OcelotOptions>>().Value;
        
        // Ocelot 23.0.0版本移除了UseOcelotAdministration方法
        // 管理API功能已在新版本中重构，暂时注释掉这部分代码
        
        // 使用Ocelot中间件
        app.UseOcelot().Wait();
        
        return app;
    }
    
    /// <summary>
    /// 使用Ocelot网关中间件（带配置操作）
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <param name="configurationAction">配置操作委托</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder UseOcelotGateway(
        this IApplicationBuilder app,
        Action<IApplicationBuilder> configurationAction)
    {
        // 执行配置操作
        configurationAction(app);
        
        // 使用Ocelot网关
        return app.UseOcelotGateway();
    }
    
    /// <summary>
    /// 使用Ocelot配置验证中间件
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder UseOcelotValidation(this IApplicationBuilder app)
    {
        return app.UseMiddleware<OcelotValidationMiddleware>();
    }
    
    /// <summary>
    /// 配置Ocelot的全局异常处理
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder ConfigureOcelotExceptionHandling(this IApplicationBuilder app)
    {
        // 全局异常处理
        app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                context.Response.StatusCode = 500;
                context.Response.ContentType = "application/json";
                
                var errorResponse = new
                {
                    Code = 500,
                    Message = "Gateway Internal Server Error",
                    Timestamp = DateTime.UtcNow
                };
                
                await context.Response.WriteAsJsonAsync(errorResponse);
            });
        });
        
        return app;
    }
}

/// <summary>
/// Ocelot配置验证中间件
/// </summary>
public class OcelotValidationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<OcelotValidationMiddleware> _logger;
    private readonly IOcelotConfigurationManager _configurationManager;
    
    /// <summary>
    /// 构造函数
    /// </summary>
    public OcelotValidationMiddleware(
        RequestDelegate next,
        ILogger<OcelotValidationMiddleware> logger,
        IOcelotConfigurationManager configurationManager)
    {
        _next = next;
        _logger = logger;
        _configurationManager = configurationManager;
    }
    
    /// <summary>
    /// 处理请求
    /// </summary>
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ocelot请求处理异常");
            
            // 如果响应尚未开始发送
            if (!context.Response.HasStarted)
            {
                context.Response.StatusCode = 502;
                context.Response.ContentType = "application/json";
                
                var errorResponse = new
                {
                    Code = 502,
                    Message = "Bad Gateway",
                    Timestamp = DateTime.UtcNow
                };
                
                await context.Response.WriteAsJsonAsync(errorResponse);
            }
        }
    }
}